<template>
    <!--地图挂载dom-->
    <div id="map">
        <div class="MapTool">
            <el-select v-model="value" placeholder="请选择" @change="drawChange">
                <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                </el-option>
            </el-select>
        </div>
    </div>
</template>

<script>
    //引入依赖
    import {Map, View} from 'ol'
    import Draw, {createBox, createRegularPolygon,} from 'ol/interaction/Draw';
    import Polygon from 'ol/geom/Polygon';
    import {OSM, Vector as VectorSource} from 'ol/source';
    import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer';
    import {Circle as CircleStyle, Fill, Icon, Stroke, Style} from 'ol/style';
    import marker from './data/marker.png'
    import {GeoJSON} from 'ol/format'
    import box from './data/box'

    export default {
        name: "DrawInteraction",
        data() {
            return {
                options: [{
                    value: 'Point',
                    label: '点'
                }, {
                    value: 'LineString',
                    label: '线'
                }, {
                    value: 'Polygon',
                    label: '面'
                }, {
                    value: 'Circle',
                    label: '圆'
                }, {
                    value: 'Square',
                    label: '正方形'
                }, {
                    value: 'Box',
                    label: '长方形'
                }, {
                    value: 'Star',
                    label: '五角星'
                }],
                value: ''
            }
        }, mounted() {
            //定义点的样式
            const image = new Icon({
                src: marker,
                anchor: [0.75, 0.5],
                rotateWithView: true,
            })
            //绘制样式
            const styles = {
                'Point': new Style({
                    image: image,
                }),
                'LineString': new Style({
                    stroke: new Stroke({
                        color: 'green',
                        width: 1,
                    }),
                }),
                'MultiLineString': new Style({
                    stroke: new Stroke({
                        color: 'green',
                        width: 1,
                    }),
                }),
                'MultiPoint': new Style({
                    image: image,
                }),
                'MultiPolygon': new Style({
                    stroke: new Stroke({
                        color: 'yellow',
                        width: 1,
                    }),
                    fill: new Fill({
                        color: 'rgba(255, 255, 0, 0.1)',
                    }),
                }),
                'Polygon': new Style({
                    stroke: new Stroke({
                        color: 'blue',
                        lineDash: [4],
                        width: 3,
                    }),
                    fill: new Fill({
                        color: 'rgba(0, 0, 255, 0.1)',
                    }),
                }),
                'GeometryCollection': new Style({
                    stroke: new Stroke({
                        color: 'magenta',
                        width: 2,
                    }),
                    fill: new Fill({
                        color: 'magenta',
                    }),
                    image: new CircleStyle({
                        radius: 10,
                        fill: null,
                        stroke: new Stroke({
                            color: 'magenta',
                        }),
                    }),
                }),
                'Circle': new Style({
                    stroke: new Stroke({
                        color: 'red',
                        width: 2,
                    }),
                    fill: new Fill({
                        color: 'rgba(255,0,0,0.2)',
                    }),
                }),
            };

            const styleFunction = function (feature) {
                return styles[feature.getGeometry().getType()];
            };
            //绘制的数据是一个矢量数据，因此需要矢量数据源和矢量图层承载
            this.source = new VectorSource({wrapX: false});
            const vector = new VectorLayer({
                source: this.source,
                style: styleFunction,
            });
            //初始化地图
            this.map = new Map({
                target: 'map',//指定挂载dom，注意必须是id
                layers: [
                    new TileLayer({
                        source: new OSM()//加载OpenStreetMap
                    }),
                    vector//提前加载矢量图层
                ],
                //配置视图
                view: new View({
                    center: [113.24981689453125, 23.126468438108688], //视图中心位置
                    projection: "EPSG:4326", //指定投影
                    zoom: 12   //缩放到的级别
                })
            });
        },
        methods: {
            drawChange(type) {
                if (this.map) {
                    //先移除之前的绘制交互对象
                    this.map.removeInteraction(this.draw);
                    this.addDraw(type)
                }

            },
            addDraw(type) {
                if (type !== 'None') {
                    //绘制函数
                    let geometryFunction;
                    if (type === 'Square') {
                        type = 'Circle';//正方形用圆绘制，分段数4
                        geometryFunction = createRegularPolygon(4);
                    } else if (type === 'Box') {
                        type = 'Circle';//使用圆的类型创建盒子
                        geometryFunction = createBox();
                    } else if (type === 'Star') {
                        type = 'Circle';
                        //绘制六角星，需要自己定义函数
                        geometryFunction = function (coordinates, geometry) {
                            const center = coordinates[0];
                            const last = coordinates[coordinates.length - 1];
                            const dx = center[0] - last[0];
                            const dy = center[1] - last[1];
                            const radius = Math.sqrt(dx * dx + dy * dy);
                            const rotation = Math.atan2(dy, dx);
                            const newCoordinates = [];
                            const numPoints = 12;
                            for (let i = 0; i < numPoints; ++i) {
                                const angle = rotation + (i * 2 * Math.PI) / numPoints;
                                const fraction = i % 2 === 0 ? 1 : 0.5;
                                const offsetX = radius * fraction * Math.cos(angle);
                                const offsetY = radius * fraction * Math.sin(angle);
                                newCoordinates.push([center[0] + offsetX, center[1] + offsetY]);
                            }
                            newCoordinates.push(newCoordinates[0].slice());
                            if (!geometry) {
                                geometry = new Polygon([newCoordinates]);
                            } else {
                                geometry.setCoordinates([newCoordinates]);
                            }
                            return geometry;
                        };
                    }

                    this.draw = new Draw({
                        type: type,//绘制的几何图形的几何类型
                        clickTolerance: 6,//点击公差
                        source: this.source,
                        geometryFunction: geometryFunction,
                        wrapX: false,//草图在x水平方向平铺
                        freehand: false//是否开启手绘模式
                    });
                    this.map.addInteraction(this.draw);
                }


                this.draw.on("drawstart", this.drawstart)
                this.draw.on("drawabort", this.drawabort)
                this.draw.on("drawend", this.drawend)

                setTimeout(() => {
                    this.draw.finishDrawing()
                    //this.map.removeInteraction(this.draw);
                }, 3000)
                this.drawMethod()
            },
            drawMethod() {

                //停止绘图而不将草图特征添加到目标图层
                //this.draw.abortDrawing()
                //停止绘制并将草图特征添加到目标图层
                //this.draw.finishDrawing()

                let coordinates = [
                    [
                        113.20793151855469,
                        23.078784229274408
                    ],
                    [
                        113.258056640625,
                        23.09647041402938
                    ]
                ];
                //将坐标附加到当前正在绘制的几何图形的末端。绘制线串或多边形时可以使用此选项
                this.draw.appendCoordinates(coordinates)
            },

            drawabort(event) {
                console.log("drawabort")
                console.log(event)
            },
            drawstart(event) {
                console.log("drawstart")
                console.log(event)
            },
            drawend(event) {
                console.log("drawend")
                console.log(event)
                if (this.draw) {
                    let feature = new GeoJSON().readFeature(box);
                    this.draw.extend(feature)
                }
            }
        }
    }
</script>

<style scoped>
    .MapTool {
        position: absolute;
        top: .5em;
        right: .5em;
        z-index: 9999;
    }
</style>